package com.leeyu.service.impl;

import com.leeyu.mapper.UserPointsMapper;
import com.leeyu.service.UserPointsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserPointsServiceImpl implements UserPointsService {

    @Autowired
    private UserPointsMapper userPointsMapper;

    @Override
    public void process(Message message) {
        // 从Message的header中获取消息id
        String MESSAGE_ID = "spring_returned_message_correlation";
        String messageId = message.getMessageProperties().getHeader(MESSAGE_ID);

        // 查询幂等表中是否存在
        int exists = userPointsMapper.existById(messageId);

        // 如果存在直接返回，避免重复消费
        if (exists > 0) {
            log.warn("消息已经被处理！！！");
            return;
        }

        // 不存在，向幂等表插入一条记录
        // 有主键唯一性约束，只有一个消费者能成功，成功才能处理消息
        // 插入重复的主键会报错，捕获异常处理更优雅
        userPointsMapper.save(messageId);

        // 模拟处理消息耗时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("预扣除用户积分成功！");
    }
}
